package offer;

/**
 * @author SSK
 * 两个链表的第一个公共结点
 */
public class T37 {

    public class ListNode {
       int val;
     ListNode next = null;

     ListNode(int val) {
          this.val = val;
      }
    }
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
          if (pHead1==null||pHead2==null) {
              return null;
          }
          int len1 = 0;
          ListNode temp = pHead1;
          while (temp!=null) {
              temp = temp.next;
              len1++;
          }
          int len2 = 0;
          temp = pHead2;
          while (temp!=null) {
              temp = temp.next;
              len2++;
          }
          if (len1>len2) {
              int cs = len1 - len2;
              while (cs>0) {
                  cs--;
                  pHead1 = pHead1.next;
              }
          }else {
              int cs = len2 - len1;
              while (cs>0) {
                  cs--;
                  pHead2 = pHead2.next;
              }
          }
          while (pHead1!=pHead2){
              pHead1 = pHead1.next;
              pHead2 = pHead2.next;
          }
          return pHead1;
    }

}
